import QtQuick 2.15
import QtQuick.Controls 2.15
import QtQuick.Layouts 1.15
import "../views/tasks" as TaskViews
import "../components" as Components
import "../styles" as Styles

Page {
    id: taskManagementScreen
    title: qsTr("任务管理")

    // 自定义属性 - 绑定到全局ViewModel
    property var taskViewModel: GlobalTaskViewModel
    property var vehicleViewModel: GlobalVehicleViewModel
    property var taskList: taskViewModel ? taskViewModel.taskListModel : []
    property var selectedTask: null
    property string filterStatus: "all"
    property string searchText: ""
    property bool showNewTaskDialog: false
    property string lastErrorMessage: ""

    background: Rectangle {
        color: Styles.Theme.background
    }

    // 主布局
    ColumnLayout {
        anchors.fill: parent
        anchors.margins: Styles.Theme.spacingNormal
        spacing: Styles.Theme.spacingNormal

        // 顶部工具栏
        Rectangle {
            Layout.fillWidth: true
            Layout.preferredHeight: 80
            color: Styles.Theme.surface
            border.color: Styles.Theme.border
            border.width: 1
            radius: Styles.Theme.radiusSmall

            RowLayout {
                anchors.fill: parent
                anchors.leftMargin: Styles.Theme.spacingNormal
                anchors.rightMargin: Styles.Theme.spacingNormal
                spacing: Styles.Theme.spacingNormal

                // 标题
                Text {
                    text: qsTr("任务管理")
                    color: Styles.Theme.textPrimary
                    font.pixelSize: Styles.Theme.fontSizeLarge
                    font.weight: Styles.Theme.fontWeightMedium
                    Layout.fillWidth: true
                }

                // 搜索框
                /*Components.SearchBar {
                    Layout.preferredWidth: 250
                    placeholderText: qsTr("搜索任务ID、AGV ID...")
                    searchText: searchText
                    onTextSearched: searchText = text
                    onSearchSubmitted: performSearch()
                }*/

                // 筛选器
                Components.CustomComboBox {
                    Layout.preferredWidth: 120
                    model: [
                        { text: qsTr("全部状态"), value: "all" },
                        { text: qsTr("待处理"), value: "pending" },
                        { text: qsTr("执行中"), value: "executing" },
                        { text: qsTr("已完成"), value: "completed" },
                        { text: qsTr("失败"), value: "failed" },
                        { text: qsTr("已取消"), value: "cancelled" }
                    ]
                    textRole: "text"
                    valueRole: "value"
                    currentIndex: 0  // 默认选中"全部状态"
                    onActivated: function(index) {
                        filterStatus = currentValue
                        applyFilter()
                    }
                }

                // 新建任务按钮
                Components.ActionButton {
                    text: qsTr("新建任务")
                    iconSource: "+"
                    buttonType: "primary"
                    onClicked: showNewTaskDialog = true
                }

                // 刷新按钮
                Components.ActionButton {
                    text: qsTr("刷新")
                    iconSource: "qrc:/icons/refresh.svg"
                    buttonType: "secondary"
                    onClicked: refreshTasks()
                }

                // 呼叫器维护模式开关 关闭任务触发
                RowLayout {
                    spacing: Styles.Theme.spacingXSmall

                    Text {
                        text: qsTr("维护模式")
                        color: Styles.Theme.textSecondary
                        font.pixelSize: Styles.Theme.fontSizeSmall
                        Layout.alignment: Qt.AlignVCenter
                    }

                    Switch {
                        id: callerSwitch
                        checked: taskViewModel ? taskViewModel.callerTriggerEnabled : true
                        onToggled: {
                            if (taskViewModel) {
                                taskViewModel.setCallerTriggerEnabled(checked)
                            }
                        }
                    }

                    Text {
                        text: callerSwitch.checked ? qsTr("开启") : qsTr("维护模式")
                        color: callerSwitch.checked ? Styles.Theme.success : Styles.Theme.warning
                        font.pixelSize: Styles.Theme.fontSizeSmall
                        Layout.alignment: Qt.AlignVCenter
                    }
                }

                // 分隔线
                Rectangle {
                    Layout.preferredWidth: 1
                    Layout.preferredHeight: 40
                    color: Styles.Theme.border
                }

                // 呼叫器连发检查开关（相同任务）
                RowLayout {
                    spacing: Styles.Theme.spacingXSmall

                    Text {
                        text: qsTr("连发限制")
                        color: Styles.Theme.textSecondary
                        font.pixelSize: Styles.Theme.fontSizeSmall
                        Layout.alignment: Qt.AlignVCenter
                    }

                    Switch {
                        id: duplicateCheckSwitch
                        checked: taskViewModel ? taskViewModel.callerDuplicateCheckEnabled : true
                        onToggled: {
                            if (taskViewModel) {
                                taskViewModel.setCallerDuplicateCheckEnabled(checked)
                            }
                        }
                    }
                }

                // 呼叫器对发检查开关（互斥任务）
                RowLayout {
                    spacing: Styles.Theme.spacingXSmall

                    Text {
                        text: qsTr("对发限制")
                        color: Styles.Theme.textSecondary
                        font.pixelSize: Styles.Theme.fontSizeSmall
                        Layout.alignment: Qt.AlignVCenter
                    }

                    Switch {
                        id: mutexCheckSwitch
                        checked: taskViewModel ? taskViewModel.callerMutexCheckEnabled : true
                        onToggled: {
                            if (taskViewModel) {
                                taskViewModel.setCallerMutexCheckEnabled(checked)
                            }
                        }
                    }
                }
            }
        }

        // 主内容区域
        RowLayout {
            Layout.fillWidth: true
            Layout.fillHeight: true
            spacing: Styles.Theme.spacingNormal

            // 左侧 - 任务列表
            Rectangle {
                Layout.fillHeight: true
                Layout.fillWidth: true
                color: Styles.Theme.surface
                border.color: Styles.Theme.border
                border.width: 1
                radius: Styles.Theme.radiusNormal

                ColumnLayout {
                    anchors.fill: parent
                    anchors.margins: Styles.Theme.spacingNormal
                    spacing: Styles.Theme.spacingSmall

                    // 列表标题栏
                    RowLayout {
                        Layout.fillWidth: true

                        Text {
                            text: qsTr("任务列表 (%1)").arg(taskViewModel ? taskViewModel.totalTaskCount : 0)
                            color: Styles.Theme.textPrimary
                            font.pixelSize: Styles.Theme.fontSizeNormal
                            font.weight: Styles.Theme.fontWeightMedium
                            Layout.fillWidth: true
                        }

                        Components.ActionButton {
                            size: "small"
                            text: qsTr("批量操作")
                            buttonType: "text"
                            onClicked: showBatchOperations()
                        }
                    }

                    // 任务数据表格
                    TaskViews.TaskDataGrid {
                        id: taskDataGrid
                        Layout.fillWidth: true
                        Layout.fillHeight: true

                        taskListModel: taskManagementScreen.taskViewModel ? taskManagementScreen.taskViewModel.taskListModel : null
                        selectedChainId: taskManagementScreen.selectedTask ? taskManagementScreen.selectedTask.chainId : ""

                        onTaskSelected: function(chainId) {
                            if (taskViewModel) {
                                var taskData = taskViewModel.getTaskDetails(chainId)
                                taskManagementScreen.selectedTask = taskData
                            }
                        }

                        onTaskDeleted: function(chainId) {
                            handleTaskDelete(chainId)
                        }
                    }
                }
            }

            // 右侧 - 任务详情和操作面板
            Rectangle {
                Layout.fillHeight: true
                Layout.preferredWidth: 450
                Layout.minimumWidth: 350
                color: Styles.Theme.surface
                border.color: Styles.Theme.border
                border.width: 1
                radius: Styles.Theme.radiusNormal

                ColumnLayout {
                    anchors.fill: parent
                    anchors.margins: Styles.Theme.spacingNormal
                    spacing: Styles.Theme.spacingNormal

                    // 任务详情标题
                    Text {
                        text: selectedTask ? qsTr("任务详情 - %1").arg(selectedTask.taskName || selectedTask.chainId || qsTr("未命名任务")) : qsTr("选择任务查看详情")
                        color: Styles.Theme.textPrimary
                        font.pixelSize: Styles.Theme.fontSizeNormal
                        font.weight: Styles.Theme.fontWeightMedium
                    }

                    // 任务详情视图
                    TaskViews.TaskDetailsView {
                        id: taskDetailsView
                        Layout.fillWidth: true
                        Layout.fillHeight: true

                        task: selectedTask
                        visible: selectedTask !== null

                        onTaskModified: function(task) {
                            handleTaskModified(task)
                        }
                    }

                    // 无选择提示
                    Rectangle {
                        Layout.fillWidth: true
                        Layout.fillHeight: true
                        color: "transparent"
                        visible: selectedTask === null

                        ColumnLayout {
                            anchors.centerIn: parent
                            spacing: Styles.Theme.spacingNormal

                            Text {
                                text: "📋"
                                font.pixelSize: 48
                                Layout.alignment: Qt.AlignHCenter
                                opacity: 0.3
                            }

                            Text {
                                text: qsTr("请选择任务")
                                color: Styles.Theme.textSecondary
                                font.pixelSize: Styles.Theme.fontSizeNormal
                                Layout.alignment: Qt.AlignHCenter
                            }

                            Text {
                                text: qsTr("从左侧列表中选择一个任务\n查看详细信息和执行操作")
                                color: Styles.Theme.textSecondary
                                font.pixelSize: Styles.Theme.fontSizeSmall
                                horizontalAlignment: Text.AlignHCenter
                                Layout.alignment: Qt.AlignHCenter
                            }
                        }
                    }

                    // 任务操作按钮区域
                    RowLayout {
                        Layout.fillWidth: true
                        visible: selectedTask !== null
                        spacing: Styles.Theme.spacingSmall

                        Components.ActionButton {
                            size: "small"
                            text: qsTr("重置子任务状态")
                            iconSource: "↺"
                            buttonType: "primary"
                            enabled: selectedTask && selectedTask.chainId
                            onClicked: resetSubTaskState(selectedTask)
                        }

                        Components.ActionButton {
                            size: "small"
                            text: qsTr("重新调度")
                            iconSource: "⟳"
                            buttonType: "secondary"
                            enabled: selectedTask && selectedTask.chainId
                            onClicked: rescheduleTask(selectedTask)
                        }

                        Item { Layout.fillWidth: true }
                    }
                }
            }
        }

        // 底部状态栏
        Rectangle {
            Layout.fillWidth: true
            Layout.preferredHeight: 30
            color: Styles.Theme.surface
            border.color: Styles.Theme.border
            border.width: 1
            radius: Styles.Theme.radiusSmall

            RowLayout {
                anchors.fill: parent
                anchors.leftMargin: Styles.Theme.spacingNormal
                anchors.rightMargin: Styles.Theme.spacingNormal

                Text {
                    text: getStatusText()
                    color: Styles.Theme.textSecondary
                    font.pixelSize: Styles.Theme.fontSizeSmall
                    Layout.fillWidth: true
                }

                Text {
                    text: qsTr("最后更新: %1").arg(formatCurrentTime())
                    color: Styles.Theme.textSecondary
                    font.pixelSize: Styles.Theme.fontSizeSmall
                }
            }
        }
    }

    // 新建任务对话框 - 使用新的无边框设计
    Components.CreateTaskDialog {
        id: newTaskDialog
        availableTemplates: taskViewModel ? taskViewModel.availableTemplates : []
        availableAgvs: vehicleViewModel ? vehicleViewModel.agvListModel : []
        taskViewModel: taskManagementScreen.taskViewModel

        onTaskAccepted: function(taskData) {
            createNewTask(taskData)
            showNewTaskDialog = false
        }
        onTaskRejected: {
            showNewTaskDialog = false
        }
        onClosed: {
            showNewTaskDialog = false
        }
    }

    // 绑定显示状态
    Connections {
        target: taskManagementScreen
        function onShowNewTaskDialogChanged() {
            if (showNewTaskDialog) {
                newTaskDialog.open()
            }
        }
    }

    // 确认对话框
    Components.ConfirmDialog {
        id: confirmDialog

        onAccepted: {
            if (callback) callback()
        }
    }

    // MAPF/任务错误提示
    Components.ConfirmDialog {
        id: errorDialog
        title: qsTr("导航提示")
        detailText: qsTr("请检查现场与路径条件后手动重发任务。")
    }

    // 事件处理函数
    function performSearch() {
        if (taskViewModel) {
            taskViewModel.searchTasks(searchText)
        }
    }

    function applyFilter() {
        // TODO: 实现筛选功能
        console.log("Apply filter:", filterStatus)
    }

    function refreshTasks() {
        if (taskViewModel) {
            taskViewModel.refreshTasks()
        }
    }

    function createNewTask(taskData) {
        if (taskViewModel) {
            var agvNumber = normalizeAgvSelection(taskData.agvId)
            console.log("Creating task from template:", taskData.templateName, "AGV:", agvNumber)
            var chainId = taskViewModel.createTaskFromTemplate(taskData.templateName, agvNumber)
            if (chainId) {
                console.log("Task created successfully:", chainId)
            } else {
                console.error("Failed to create task")
            }
        }
    }

    function normalizeAgvSelection(value) {
        if (value === undefined || value === null || value === "") {
            return -1
        }

        var numeric = Number(value)
        if (isNaN(numeric)) {
            console.warn("Invalid AGV selection, fallback to auto:", value)
            return -1
        }

        return numeric
    }

    function handleTaskDoubleClick(task) {
        // 双击打开任务详情对话框
        console.log("Open task details dialog for:", task.chainId)
    }

    function handleTaskDelete(chainId) {
        if (taskViewModel) {
            var success = taskViewModel.cancelTask(chainId)
            if (success) {
                console.log("Task deleted:", chainId)
                refreshTasks()
            } else {
                console.error("Failed to delete task:", chainId)
            }
        }
    }

    function handleTaskAction(action, task) {
        switch(action) {
            case "cancel":
                cancelTask(task)
                break
            case "retry":
                retryTask(task)
                break
            case "adjust_priority":
                adjustTaskPriority(task)
                break
            default:
                console.log("Unknown task action:", action)
        }
    }

    function handleTaskModified(task) {
        if (taskViewModel) {
            taskViewModel.updateTask(task)
        }
    }

    function resetSubTaskState(task) {
        if (!task || !taskViewModel || !task.chainId) {
            return
        }
        confirmDialog.title = qsTr("重置子任务状态")
        confirmDialog.messageText = qsTr("确定将任务 %1 的当前子任务重置到初始化状态吗？").arg(task.taskName || task.chainId)
        confirmDialog.detailText = qsTr("此操作会重新执行当前子任务。")
        confirmDialog.callback = function() {
            taskViewModel.resetCurrentSubTask(task.chainId)
        }
        confirmDialog.open()
    }

    function cancelTask(task) {
        confirmDialog.title = qsTr("确认取消任务")
        confirmDialog.messageText = qsTr("确定要取消任务 %1 吗？").arg(task.taskName || task.chainId)
        confirmDialog.detailText = qsTr("此操作不可撤销。")
        confirmDialog.callback = function() {
            if (taskViewModel) {
                taskViewModel.cancelTask(task.chainId)
            }
        }
        confirmDialog.open()
    }

    function adjustTaskPriority(task) {
        // TODO: 打开优先级调整对话框
        console.log("Adjust priority for task:", task.chainId)
    }

    function retryTask(task) {
        confirmDialog.title = qsTr("确认重新执行")
        confirmDialog.messageText = qsTr("确定要重新执行任务 %1 吗？").arg(task.taskName || task.chainId)
        confirmDialog.detailText = ""
        confirmDialog.callback = function() {
            if (taskViewModel && typeof taskViewModel.retryTask === "function") {
                taskViewModel.retryTask(task.chainId)
            } else {
                console.warn("Retry operation is not available in current build.")
            }
        }
        confirmDialog.open()
    }

    function rescheduleTask(task) {
        if (!task || !taskViewModel || !task.chainId) {
            return
        }
        confirmDialog.title = qsTr("重新调度")
        confirmDialog.messageText = qsTr("重新调度任务 %1 ？").arg(task.taskName || task.chainId)
        confirmDialog.detailText = qsTr("将触发对当前任务的路径重新求解。")
        confirmDialog.callback = function() {
            if (typeof taskViewModel.rescheduleAgv === "function") {
                taskViewModel.rescheduleAgv(task.agvNumber || -1)
            } else {
                console.warn("Reschedule operation is not available in current build.")
            }
        }
        confirmDialog.open()
    }

    function showBatchOperations() {
        // TODO: 显示批量操作面板
        console.log("Show batch operations")
    }

    function getStatusText() {
        if (!taskViewModel) {
            return qsTr("等待连接...")
        }

        var pending = 0
        var executing = taskViewModel.activeTaskCount || 0
        var completed = taskViewModel.completedTaskCount || 0
        var failed = taskViewModel.failedTaskCount || 0

        return qsTr("待处理: %1 | 执行中: %2 | 已完成: %3 | 失败: %4")
            .arg(pending).arg(executing).arg(completed).arg(failed)
    }

    function formatCurrentTime() {
        return new Date().toLocaleTimeString()
    }

    // 组件初始化
    Component.onCompleted: {
        console.log("TaskManagementScreen: Initializing...")
        console.log("TaskViewModel available:", taskViewModel !== null)

        if (taskViewModel) {
            console.log("TaskViewModel connected successfully")
            // 连接信号
            taskViewModel.taskCreated.connect(function(chainId) {
                console.log("Task created:", chainId)
            })
            taskViewModel.errorOccurred.connect(function(message) {
                console.error("Task error:", message)
                const err = message || qsTr("未知错误")
                taskManagementScreen.lastErrorMessage = err
                errorDialog.messageText = err
                errorDialog.open()
            })

            // 初始刷新
            refreshTasks()
        } else {
            console.warn("TaskViewModel not available - using demo data")
            createDemoTasks()
        }
    }

    // 创建一些模拟任务数据
    function createDemoTasks() {
        console.log("TaskManagementScreen: Creating demo tasks...")
        taskList = [
            {
                chainId: "T001",
                taskName: "运输零件到装配线",
                status: "executing",
                currentTaskIndex: 1,
                totalTasks: 4,
                progress: 40,
                assignedAgv: "AGV001",
                createTime: Date.now() - 3600000,
                durationSeconds: 3600,
                currentSubTask: "Move to A01",
                currentSubTaskStage: 1
            },
            {
                chainId: "T002",
                taskName: "搬运原材料",
                status: "pending",
                currentTaskIndex: 0,
                totalTasks: 3,
                progress: 0,
                assignedAgv: "",
                createTime: Date.now() - 1800000,
                durationSeconds: 1800,
                currentSubTask: "",
                currentSubTaskStage: 0
            },
            {
                chainId: "T003",
                taskName: "成品出库",
                status: "completed",
                currentTaskIndex: 4,
                totalTasks: 4,
                progress: 100,
                assignedAgv: "AGV002",
                createTime: Date.now() - 7200000,
                durationSeconds: 7000,
                currentSubTask: "Park",
                currentSubTaskStage: 3
            },
            {
                chainId: "T004",
                taskName: "设备维护物料运输",
                status: "failed",
                currentTaskIndex: 2,
                totalTasks: 4,
                progress: 50,
                assignedAgv: "AGV003",
                createTime: Date.now() - 5400000,
                durationSeconds: 5400,
                currentSubTask: "Lift",
                currentSubTaskStage: 2
            }
        ]
        console.log("TaskManagementScreen: Created", taskList.length, "demo tasks")
    }
}
